package com.yycx.module.bus.provider.handler.process.form;

import com.alibaba.fastjson.util.TypeUtils;
import com.yycx.bpm.provider.handler.TaskCompleteHandler;
import com.yycx.bpm.provider.model.TaskRequest;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.security.OpenUser;
import com.yycx.common.utils.DateUtils;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.module.bus.client.entity.*;
import com.yycx.module.bus.provider.service.*;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 获取任务表单数据
 *
 * @author zyf
 */
@Component
public class ConsumptionFormTaskDataHandler implements TaskCompleteHandler {

    @Autowired
    private BusConsumptionService busConsumptionService;

    @Autowired
    private BusPaymentService paymentService;


    @Override
    public Map<String, Object> initTaskData(ProcessInstance processInstance, Task task, Map<String, Object> variables) {
        Map<String, Object> ret = new HashMap<>(5);
        String businessKey = processInstance.getBusinessKey();
        BusConsumption busConsumption = busConsumptionService.getById(businessKey);
        if (FlymeUtils.isNotEmpty(busConsumption)) {
            ret.put("bankName", busConsumption.getBank());
            ret.put("bankNo", busConsumption.getBankNo());
            ret.put("paymentId", busConsumption.getConsumptionId());
            ret.put("payAmount", busConsumption.getApplyAmount());
            ret.put("userName", busConsumption.getReceivingUnit());

        }
        return ret;
    }

    /**
     * 表单提交后业务处理
     *
     * @param taskRequest
     * @param processInstance
     * @param task
     * @param completeVariables
     */
    @Override
    public void completeAfter(TaskRequest taskRequest, ProcessInstance processInstance, Task task, Map<String, Object> completeVariables, OpenUser user) {
        String businessKey = processInstance.getBusinessKey();
        BusConsumption busConsumption = busConsumptionService.getById(businessKey);
        Object payBankId = completeVariables.get("payBankId");
        Object payDate = completeVariables.get("payDate");
        if (FlymeUtils.isNotEmpty(busConsumption)) {
            busConsumption.setPayDate(DateUtils.parseDate(payDate.toString()));
            busConsumption.setPayBankId(TypeUtils.castToLong(payBankId));
            busConsumption.setPayUserId(user.getUserId());
            busConsumption.setCheckState(CommonConstants.INT_2);
            busConsumptionService.updateById(busConsumption);
            paymentService.updatePaymentState(busConsumption.getConsumptionId(),CommonConstants.INT_2,user.getUserId(),payDate.toString());
        }
    }

}
